package com.gok.pay.exception;

import com.gok.pay.base.RestResult;
import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;


@Slf4j
@ControllerAdvice
@RestController
public class CommonExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity resolveException(HttpServletRequest request, Exception e) {
        //e.printStackTrace();
        String uuid = StringUtils.left(logError(e), 10);
        if (e instanceof AuthenticationException) {
            return ResponseEntity.badRequest().body(RestResult.failureDefault("账号或密码输入错误啦" + uuid));
        } else if (e instanceof UnauthorizedException) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(RestResult.failureDefault("请重新登录" + uuid));
        } else if (e instanceof NullPointerException) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(RestResult.failureDefault("NPE" + uuid));
        } else if(e instanceof MySQLSyntaxErrorException){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(RestResult.failureDefault("数据库异常" + uuid));
        }else{
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(RestResult.failureDefault("忙不过来啦，请等等" + uuid));
        }

    }

    private String logError(Exception e) {
        log.error("Exception caught by CommonExceptionHandler, exception info：" + e.getMessage(), e);
        String uuid = UUID.randomUUID().toString();
        log.error(uuid + "CommonExceptionHandler");
        return uuid;
    }
}
